function saveNiiResults(Params)
% function generates nii files from the computed results
% Juha Pajula, 14.4.2015

disp('Saving results to nii:')
Priv = Params.PrivateParams;
Pub = Params.PublicParams;

%load Memmaps and one original source nii to get the voxel dimensions
load([Pub.dataDestination 'memMaps'])
nii_orighdr = load_nii(Pub.subjectSource{1});

if(strcmp(Pub.fileFormat,'nii')) %if the data is nii and it is possible to get the correct voxel dimensions and origin
    voxdim = nii_orighdr.hdr.dime.pixdim(2:4);
    origin = nii_orighdr.hdr.hist.originator(1:3)-1; %note matlab indexing fix -1
else %if the data is matlab mat files there is no information for header available
    voxdim=[];
    origin=[];
end

disp('   Saving the correlation statistics')
for nrBand = 0:Pub.nrFreqBands
    disp(['      Band ' num2str(nrBand)])
    for nrSession = 1:Priv.nrSessions
        disp(['         Session ' num2str(nrSession)])
        %read the data from the memmaps
        img=memMaps.resultMap.whole.(['band' num2str(nrBand)]).(['Session' num2str(nrSession)]).cor.Data.xyz;
        
        % generate nii structure
        nii_out = make_nii(img, voxdim,origin,[],'ISCtoolbox');
        %nii_out = make_nii(img, Priv.dataSize(nrSession,1:3) ,[],[],'ISCtoolbox');
        
        % save the nii to the result folder of destination
        save_nii(nii_out,[Priv.resultsDestination 'ISCcorrmapBand' num2str(nrBand) 'Session' num2str(nrSession) '.nii']);
        
        if(Priv.nrTimeIntervals(nrSession) ~= 0)
            disp('   Saving the timewindow correlation maps')
            img = zeros([memMaps.resultMap.win.([Priv.prefixFreqBand num2str(nrBand)]).([Priv.prefixSession num2str(nrSession)]).cor.Format{2} Priv.nrTimeIntervals(nrSession)]);
            
            for wfr = 1:Priv.nrTimeIntervals(nrSession)
                disp(['         Time window ' num2str(wfr)])
                img(:,:,:,wfr) = memMaps.resultMap.win.([Priv.prefixFreqBand num2str(nrBand)]).([Priv.prefixSession num2str(nrSession)]).cor.Data(wfr).xyz;
                %nii_out = make_nii(img, [Priv.dataSize(nrSession,1:3)] ,[],[],'ISCtoolbox');
            end
            
            nii_out = make_nii(img, voxdim,origin,[],'ISCtoolbox');
            
            % save the nii to the result folder of destination
            save_nii(nii_out,[Priv.resultsDestination 'ISCcorrmapTimeWinBand' num2str(nrBand) 'Session' num2str(nrSession) '.nii']);
        end
    end
end



if Params.PublicParams.freqCompOn
    disp('   Saving the frequency band comparisons')
    freqComps = ((Priv.maxScale+2)^2-(Priv.maxScale+2))/2;
    % nrSubjPairs = ((Priv.nrSubjects)^2-(Priv.nrSubjects))/2;
    % here comes the save nii based on:
    % PearsonFilon(Params,nrSession,freqComp);
    
    for nrSession = 1:Priv.nrSessions
        disp(['      Session ' num2str(nrSession)])
        mMapmatResultWhole = memMaps.(Priv.PFmatMapName).whole.([Priv.prefixSession num2str(nrSession)]).cor;
        for fr = 1:freqComps
            disp(['         Frequency comparison ' num2str(fr)])
            %get the data
            img=mMapmatResultWhole.([Priv.prefixFreqComp num2str(fr)]).Data.xyzc;
            % generate nii structure
            %nii_out = make_nii(img, [Priv.dataSize(nrSession,1:3)] ,[],[],'ISCtoolbox');
            nii_out = make_nii(img, voxdim,origin,[],'ISCtoolbox');
            
            
            % save the nii to the result folder of destination
            save_nii(nii_out,[Priv.resultsDestination 'ISCPFmatMapFreqComp' num2str(fr) 'Session' num2str(nrSession) '.nii']);
            
        end
    end
end

if Params.PublicParams.calcCorMatrices
    % here comes the save nii based on:
    % calculateCorMats(Params,nrBand,nrSession);
    %
end

if Params.PublicParams.calcStats
    % here comes the save nii based on:
    % calculateStatsMaps(Params,nrBand,nrSession);
    %
    disp('   Saving the extra statistics maps')
    mMapStat = memMaps.(Priv.statMapName);
    map_labels = {'meanFisher','stdFisher', 'lowerQuarter', 'median', 'upperQuarter'};
    for nrBand = 0:Pub.nrFreqBands
        disp(['      Band ' num2str(nrBand)])
        for nrSession = 1:Priv.nrSessions
            disp(['         Session ' num2str(nrSession)])
            img = mMapStat.whole.([Priv.prefixFreqBand num2str(nrBand)]).([Priv.prefixSession num2str(nrSession)]).cor.Data.xyz;
            nii_out = make_nii(img, voxdim,origin,[],'ISCtoolbox');
            %           nii_out = make_nii(img, [Priv.dataSize(nrSession,1:3)] ,[],[],'ISCtoolbox');
            
            % save the nii to the result folder of destination
            save_nii(nii_out,[Priv.resultsDestination 'ISCstatmapBand' num2str(nrBand) 'Session' num2str(nrSession) '.nii']);
            
            %if time window analysis is selected
            if(Priv.nrTimeIntervals(nrSession) ~= 0)
                img = zeros([mMapStat.win.([Priv.prefixFreqBand num2str(nrBand)]).([Priv.prefixSession num2str(nrSession)]).cor.Format{2}, Priv.nrTimeIntervals(nrSession)]);
                for wfr = 1:Priv.nrTimeIntervals(nrSession)
                    disp(['         Time window ' num2str(wfr)])
                    img(:,:,:,:,wfr) = mMapStat.win.([Priv.prefixFreqBand num2str(nrBand)]).([Priv.prefixSession num2str(nrSession)]).cor.Data(wfr).xyz;
                end
                for k = 1:5
                    img_tmp = squeeze(img(:,:,:,k,:));
                    %nii_out = make_nii(img, [Priv.dataSize(nrSession,1:3)] ,[],[],'ISCtoolbox');
                    nii_out = make_nii(img_tmp, voxdim,origin,[],'ISCtoolbox');
                    % save the nii to the result folder of destination
                    %                save_nii(nii_out,[Priv.resultsDestination 'ISCstatmapWin' num2str(wfr) 'Band' num2str(nrBand) 'Session' num2str(nrSession) '.nii']);
                    save_nii(nii_out,[Priv.resultsDestination 'ISCstatmapTimeWinBand' num2str(nrBand) 'Session' num2str(nrSession), map_labels{k} '.nii']);
                end
            end
        end
    end
end

if Params.PublicParams.calcPhase
    % here comes the save nii based on:
    % calculatePhaseSynch(Params,nrBand,nrSession);
    %
end

if Params.PublicParams.calcPhase || Params.PublicParams.winOn
    % here comes the save nii based on:
    % calculateSynchCurves(Params,nrBand,nrSession);
end

if Params.PublicParams.sessionCompOn
    disp('   Saving the session comparison maps')
    sessBlock = ((Priv.nrSessions)^2-(Priv.nrSessions))/2;
    for nrBand = 0:Pub.nrFreqBands
        for fr = 1:length(sessBlock)
            mMapmatResultWhole = memMaps.(Priv.PFmatMapSessionName).whole.([Priv.prefixFreqBand num2str(nrBand)]).cor;
            img = mMapmatResultWhole.([Priv.prefixSessComp num2str(sessBlock(fr))]).Data.xyzc;
            img_tmp = sum(img,4);
            nii_out = make_nii(img, voxdim,origin,[],'ISCtoolbox');
            % save the nii to the result folder of destination
            save_nii(nii_out,[Priv.resultsDestination 'ISCSessionComp' num2str(fr) 'Band' num2str(nrBand) '.nii']);
            
            nii_out = make_nii(img_tmp, voxdim,origin,[],'ISCtoolbox');
            save_nii(nii_out,[Priv.resultsDestination 'ISCSessionComp' num2str(fr) 'Band' num2str(nrBand) 'ZSum.nii']);
        end
    end
end
clear memMaps;